﻿#include <QElapsedTimer>

#include "BaseController.h"
#include "WaitUtils.h"
#include "DeviceManager.h"
#include "NotificationManager.h"
#include "DialogControl.h"

BaseController::BaseController(QObject *parent) : BaseItem(parent)
{
}

BaseController::~BaseController()
{
    _mgr->deleteLater();
}

QStringList BaseController::GetCommandNames()
{
    QStringList ret;
    for(auto cmd:_allCommands)
    {
        ret.append(cmd->Name());
    }
    return ret;
}

QList<BaseCommand*> BaseController::GetCommands()
{
    return _allCommands;
}

BaseCommand *BaseController::GetCommand(QString name)
{
    for(auto cmd:_allCommands)
    {
        if(cmd->Name()==name)
        {
            return cmd;
        }
    }
    throw QString("BaseController::GetCommand 未找到%0指令!").arg(name);
}

void BaseController::ExecuteWrap(BaseCommand *cmd)
{
    QElapsedTimer ela;
    ela.start();
    qDebug()<<"---"<<cmd->Name()<<"开始运行";
    WaitUtils::WaitMsNoProgress(10);
    cmd->Execute();
    WaitUtils::WaitMsNoProgress(10);
    qDebug()<<"---"<<"指令执行完毕 "<<ela.elapsed()/1000<<"s";
}

void BaseController::ExecuteWrap(QList<BaseCommand *> cmds)
{
    CheckWeightSum(cmds,100);
    QElapsedTimer ela;
    ela.start();
    qDebug()<<"总流程开始:"<<cmds.count()<<" command";
    WaitUtils::Reset();
    NotificationManager &report=NotificationManager::Instance();
    report.Reset();

    for(int i=0;i<cmds.count();i++)
    {
        BaseCommand *curCmd=cmds.at(i);
        int weight=curCmd->GetWeight();
        if(curCmd->GetSubCommands().count()==0)
        {
            report.AddBaseProgress(weight);
        }
        report.SetCurrentFlow(cmds.at(i)->GetFriendlyName());
        ExecuteWrap(cmds.at(i));
        report.UpdateProgress(100);
    }
    qDebug()<<"总流程结束 "<<ela.elapsed()/1000<<"s";
}

void BaseController::CheckWeightSum(QList<BaseCommand *> cmds,int sumWeight)
{
    int sum=0;
    foreach (BaseCommand *it, cmds) {
        sum+=it->GetWeight();
    }
    qDebug()<<__FUNCTION__<<__LINE__<<sum;
    if(sum!=sumWeight)
    {
        throw QString("所有指令权重总错误!当前:%1 目标:%2").arg(sum).arg(sumWeight);
    }
}

void BaseController::Stop()
{
    WaitUtils::Stop();
    DeviceManager::Instance().Stop();
}

void BaseController::SetConfig(QJsonObject obj)
{
    BaseItem::SetConfig(obj);
}

QWidget *BaseController::GetConfigWidget()
{
    DialogControl *w=new DialogControl();
    w->SetController(this);
    return w;
}



